package tencentcloud

import (
	appv1 "gitee.com/amoyx/devops-infras/api/v1"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	tse "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/tse/v20201207"
)

type NacosCloud interface {
	CreateNacos(nacos *appv1.Nacos) (*tse.CreateEngineResponse, error)
	DeleteNacos(id string) (*tse.DeleteEngineResponse, error)
	QueryNacos(id string) (*tse.DescribeSREInstancesResponse, error)
	QueryAccessAddress(id string) (*tse.DescribeSREInstanceAccessAddressResponse, error)
	UpdateInternetAccess(id string, isEnabled bool) error
}

// QueryNacos 查询nacos实例
func (r *RealTencentCloud) QueryNacos(id string) (response *tse.DescribeSREInstancesResponse, err error) {
	request := tse.NewDescribeSREInstancesRequest()
	request.Filters = []*tse.Filter{
		&tse.Filter{
			Name:   common.StringPtr("InstanceId"),
			Values: common.StringPtrs([]string{id}),
		},
	}
	response, err = r.tseClient.DescribeSREInstances(request)
	return
}

// CreateNacos 创建nacos实例
func (r *RealTencentCloud) CreateNacos(nacos *appv1.Nacos) (response *tse.CreateEngineResponse, err error) {
	request := tse.NewCreateEngineRequest()
	request.EngineType = common.StringPtr("nacos")
	request.EngineVersion = common.StringPtr(nacos.Spec.EngineVersion)
	request.EngineProductVersion = common.StringPtr("STANDARD")
	request.EngineRegion = common.StringPtr("ap-shanghai")
	request.EngineResourceSpec = common.StringPtr(nacos.Spec.EngineResourceSpec)
	request.EngineNodeNum = common.Int64Ptr(3)
	request.VpcId = common.StringPtr(nacos.Spec.VpcId)
	request.SubnetId = common.StringPtr(nacos.Spec.Subnet)
	request.EngineName = common.StringPtr(nacos.Spec.Name)
	request.TradeType = common.Int64Ptr(0)
	request.PrepaidPeriod = common.Int64Ptr(1)
	request.PrepaidRenewFlag = common.Int64Ptr(1)

	response, err = r.tseClient.CreateEngine(request)
	return
}

// QueryAccessAddress 查询访问地址
func (r *RealTencentCloud) QueryAccessAddress(id string) (*tse.DescribeSREInstanceAccessAddressResponse, error) {
	request := tse.NewDescribeSREInstanceAccessAddressRequest()
	request.InstanceId = common.StringPtr(id)
	response, err := r.tseClient.DescribeSREInstanceAccessAddress(request)
	return response, err
}

// UpdateInternetAccess 开启或关闭公网地址访问
func (r *RealTencentCloud) UpdateInternetAccess(id string, isEnabled bool) error {
	request := tse.NewUpdateEngineInternetAccessRequest()
	request.InstanceId = common.StringPtr(id)
	request.EnableClientInternetAccess = common.BoolPtr(isEnabled)
	request.EngineType = common.StringPtr("nacos")
	_, err := r.tseClient.UpdateEngineInternetAccess(request)
	return err
}

// DeleteNacos 删除nacos实例
func (r *RealTencentCloud) DeleteNacos(id string) (response *tse.DeleteEngineResponse, err error) {
	request := tse.NewDeleteEngineRequest()
	request.InstanceId = common.StringPtr(id)
	response, err = r.tseClient.DeleteEngine(request)
	return
}
